def create_inverted_index(documents):
    inverted_index = {}
    for doc_id, document in enumerate(documents):
        for word in document.split():
            if word not in inverted_index:
                inverted_index[word] = set()
            inverted_index[word].add(doc_id)
    return inverted_index


def query_inverted_index(inverted_index, query):
    query_terms = query.split()
    result = set()
    for term in query_terms:
        if term in inverted_index:
            result.update(inverted_index[term])
    return result


if __name__ == '__main__':

    # 示例文档集合
    documents = [
        "This is the first document",
        "This document is the second document",
        "And this is the third one",
        "Is this the first document"
    ]

    # 创建倒排索引
    inverted_index = create_inverted_index(documents)
    print(f"倒排索引:", inverted_index)
    # 查询索引
    query = "first document"
    result = query_inverted_index(inverted_index, query)

    # 输出查询结果
    print(f"查询 '{query}' 的结果:")
    for doc_id in result:
        print(f"文档ID: {doc_id}, 内容: {documents[doc_id]}")
